﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.MySQL;
//using Volo.Abp.EntityFrameworkCore.Oracle;
//using Volo.Abp.EntityFrameworkCore.Oracle.Devart;
using Volo.Abp.EntityFrameworkCore.PostgreSql;
using Volo.Abp.EntityFrameworkCore.Sqlite;
using Volo.Abp.EntityFrameworkCore.SqlServer;
using Volo.Abp.Modularity;
using Xms.Abp.Modularity;

namespace Xms.Abp.Storage;

[DependsOn(
    typeof(AbpEntityFrameworkCoreMySQLModule),
    typeof(AbpEntityFrameworkCorePostgreSqlModule),
    typeof(AbpEntityFrameworkCoreSqliteModule),
    typeof(AbpEntityFrameworkCoreSqlServerModule)
    //,
    //typeof(AbpEntityFrameworkCoreOracleDevartModule)
    )]
public class XmsAbpStorageModule : XmsModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        base.ConfigureServices(context);

        var configuration = context.Services.GetConfiguration().GetSection("DbContextOptions");

        var isSensitiveDataLoggingEnabled = configuration.GetValue<bool>("IsSensitiveDataLoggingEnabled");
        var dbType = configuration["DefaultDbType"]?.ToLower();
        context.Services.Configure<AbpDbContextOptions>(options =>
        {
            options.Configure(ctx =>
            {
                var builder = dbType switch
                {
                    "postgresql" => ctx.UseNpgsql(),
                    "sqlserver" => ctx.UseSqlServer(),
                    //"oracle" => ctx.UseOracle(),
                    "sqlite" => ctx.UseSqlite(),
                    "mysql" => ctx.UseMySQL(),
                    _ => ctx.UseMySQL()
                };
                ctx.DbContextOptions.EnableSensitiveDataLogging(isSensitiveDataLoggingEnabled);
                //ctx.DbContextOptions.ReplaceService<IModelCacheKeyFactory, XmsModelCacheKeyFactory>();
            });
        });

        Configure<DbContextOptions>(options =>
        {
            options.WithExtension(new CoreOptionsExtension().WithSensitiveDataLoggingEnabled(isSensitiveDataLoggingEnabled));
        });
    }
}

